<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2023/2/4
 * Time: 16:58
 */

namespace app\api\controller;

use think\Db;

class Giftbagstore extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;

    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }

    /**
     * 申请礼包店铺
     * bs_yingye     营业执照
     * bs_mentou     门头照
     * bs_lon        经度
     * bs_lat        纬度
     * bs_address    详细地址
     * bs_phone      手机号
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function applyStore(){
        $bs_yingye = input('bs_yingye');
        $bs_mentou = input('bs_mentou');
        $bs_lon = input('bs_lon');
        $bs_lat = input('bs_lat');
        $bs_address = input('bs_address');
        $bs_phone = input('bs_phone');

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_giftbag_level')->find();
        if($user['user_giftbag_level'] == 1){
            return json(['status' => 0, 'msg' => '您的权限不足，请先购买礼包或者联系管理员']);
        }

        $data = [
            'bs_yingye' => $bs_yingye,
            'bs_mentou' => $bs_mentou,
            'bs_lon' => $bs_lon,
            'bs_lat' => $bs_lat,
            'bs_address' => $bs_address,
            'bs_phone' => $bs_phone
        ];
        $alreadyApply = Db::table('up_bo_giftbag_store')->where('bs_user_id', $this->user_id)->find();
        if($alreadyApply){
            $data['bs_status'] = 1;
            $data['bs_refuse_reason'] = '';
            $data['bs_update_time'] = $this->create_time;

            $res = Db::table('up_bo_giftbag_store')->where('bs_id', $alreadyApply['bs_id'])->update($data);
        }else{
            $data['bs_user_id'] = $this->user_id;
            $data['bs_time'] = $this->create_time;
            $res = Db::table('up_bo_giftbag_store')->insert($data);
        }
        if($res){
            return json(['status' => 200, 'msg' => '您的申请已提交，请耐心等待']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }

    /**
     * 店铺申请状态
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function applyStatus(){
        $store = Db::table('up_bo_giftbag_store')
            ->where('bs_user_id', $this->user_id)
            ->field('bs_status')
            ->find();
        if(!$store){
            $status = 0; // 未申请过
        }else{
            $status = $store['bs_status'];
        }
        return json(['status' => 200, 'msg' => $status]);
    }

    /**
     * 店铺信息回显
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showStoreInfo(){
        $store = Db::table('up_bo_giftbag_store')
            ->where('bs_user_id', $this->user_id)
            ->field('bs_user_id, bs_time, bs_update_time', true)
            ->find();
        return json(['status' => 200, 'msg' => $store]);
    }

    /**
     * 加入会员
     * vip_code     会员码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function joinVip(){
        $vip_code = input('vip_code');
        $store = Db::table('up_bo_giftbag_store')->where('bs_vip_code', $vip_code)->field('bs_status, bs_id, bs_user_id')->find();
        if(!$store) return json(['status' => 0, 'msg' => '暂无店铺信息']);
        if($store['bs_status'] != 2){
            return json(['status' => 0, 'msg' => '该店铺未审核通过，不可加入']);
        }

//        if($store['bs_user_id'] == $this->user_id){
//            return json(['status' => 0, 'msg' => '不可以加入自己的店铺']);
//        }

        $user = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->field('user_giftbag_level, user_giftbag_store_id, user_giftbag_store_time, user_zeng_get_type')
            ->find();

        if($user['user_zeng_get_type'] == 2){
            return json(['status' => 0, 'msg' => '已领取面膜，无法加入']);
        }
        if($user['user_giftbag_level'] == 1){
            return json(['status' => 1, 'msg' => '您的权限不足，请先购买礼包或者联系管理员']);
        }
        if($user['user_giftbag_store_id']){
            if($user['user_giftbag_store_id'] != $store['bs_id']){
                return json(['status' => 0, 'msg' => '您已是其它店铺会员']);
            }else{
                return json(['status' => 0, 'msg' => '您已加入店铺，请不要重复加入']);
            }
        }

        $orders = Db::table('up_bo_orderg')
            ->join('up_bo_giftbag', 'gift_id = bog_gift_id', 'LEFT')
            ->where(['bog_user_id' => $this->user_id, 'bog_is_pay' => 2])
            ->field('bog_id, gift_indate')
            ->select();

        $update = ['user_giftbag_store_id' => $store['bs_id'], 'user_giftbag_store_time' => $this->create_time];

        Db::startTrans();
        try{
            // 更新用户所属店铺ID
            Db::table('up_u_user')
                ->where('user_id', $this->user_id)
                ->update($update);

            // 更新用户所有礼包订单有效期、剩余时间、剩余礼包数
            if($orders){
                foreach ($orders as $k => $order){
                    $limit = $order['gift_indate'] - 2;
                    $indate = date('Y-m', strtotime("last day of +{$limit} months"));
                    Db::table('up_bo_orderg')
                        ->where('bog_id', $order['bog_id'])
                        ->update([
                            'bog_indate' => $indate,
                            'bog_indate_month' => $order['gift_indate'] - 1,
                            'bog_zeng_number' => $order['gift_indate'] - 1,
                        ]);
                }
            }

            Db::commit();
            return json(['status' => 200, 'msg' => '恭喜加入成功']);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
}